import React, { useRef, useState,useEffect } from "react";
import { /*RFValue*/ } from "react-native-responsive-fontsize";
import { Button, ScrollView, StyleSheet, Text, TouchableOpacity, View,TextInput, Alert,Platform } from "react-native";
import { ArrowBackIcon,NativeBaseProvider,TextArea,Image,AddIcon,useToast,CloseIcon} from "native-base";
import * as S from "../Home/styles";
import {launchImageLibrary,launchCamera} from 'react-native-image-picker';
import { feedback } from "../../services/user";
import axios from 'axios';
import { useGlobal } from '../../utils/GlobalContext';
import { showToast } from "../../utils/toast";





const Title = ({navigation}:any)=>{
  return(
    <View style={styles.titleBox}>
      <TouchableOpacity
        style={styles.backBtn}
        onPress={() => {
          navigation.goBack()
        }}
      >
        <ArrowBackIcon size="5" />
      </TouchableOpacity>
      <Text style={styles.titlText}>问题反馈</Text>
    </View>
  )
}

const TypeList = ({setData}:any) => {
  const [ selectLevelIndex, setSelectLevelIndex ] = useState(1);

  const setLeve = (type:number)=>{
    setSelectLevelIndex(type)
    setData(type.toString(),1)
  }
  return (
    <View style={styles.levelOneTop}>
      <TouchableOpacity
        style={[styles.levelOneButton, selectLevelIndex === 1 ? styles.levelOneButtonActive : {}]}
        onPress={() => setLeve(1)}
      >
        <Text style={[selectLevelIndex === 1 ? {fontWeight:'700'} : {},styles.buttonText]}>BUG反馈</Text>
      </TouchableOpacity>
      <TouchableOpacity
         style={[styles.levelOneButton, selectLevelIndex === 2 ? styles.levelOneButtonActive : {}]}
        onPress={() => setLeve(2)}
      >
        <Text style={[selectLevelIndex === 2 ? {fontWeight:'700'} : {},styles.buttonText]}>设计建议</Text>
      </TouchableOpacity>
      <TouchableOpacity
         style={[styles.levelOneButton, selectLevelIndex === 3 ? styles.levelOneButtonActive : {}]}
        onPress={() => setLeve(3)}
      >
        <Text style={[selectLevelIndex === 3 ? {fontWeight:'700'} : {},styles.buttonText]}>其他</Text>
      </TouchableOpacity>
    </View>
  )


}

const TextAreaBox = ({setData}:any)=>{
  const [ content, setContent ] = useState('');
  const setTextAreaValue = (text)=>{
    setContent(text)
    setData(text,2)
  }
  return (
    <View style={styles.inputBox}>
       <Text style={styles.inpitTitle}>
          反馈内容
        </Text>
      <TextArea value={content} onChangeText={text => setTextAreaValue(text)} autoCompleteType="" bgColor="#fff" padding={0} borderColor="#fff" focusOutlineColor="#fff " h={120} fontSize={16} placeholder="输入需要反馈的内容" w="100%" />

    </View>
  )
}

const ImageUpload = ({setData}:any)=>{
  const [imgList, setimgList] = useState([])

  const pickImage = () => {
    launchImageLibrary(
      {
        mediaType: 'photo',
        selectionLimit: 6,
        includeBase64: false,
        maxWidth: 500,
        maxHeight: 500,
        quality:0.5
      },
      async res => {
        // console.log(res)
        const curFiles = res.assets;
        let result = []
        for(var i = 0; i < curFiles.length; i++){
          // console.log(curFiles[i]);
          // result=curFiles[i]
          // await setimgList([...imgList,curFiles[i]])
          result.push(curFiles[i])
        }   
        // console.log(imgList)
        await setimgList([...imgList,...result])
        setData([...imgList,...result],3)
      }
      )
  };

  useEffect(() => {
    // init()
    console.log(1231)
    return () => {

    };



  }, [imgList]);
  const delImage =  async (index:any)=>{
    setimgList(imgList.filter((item,i) => i !== index))
  }


  return(
    <View style={styles.inputBox}>
      <Text style={styles.inpitTitle}>
        上传图片
      </Text>
      <View style={styles.iamgeContent}>
        {imgList.map((item,index)=>{
          return (
            <View key={index} style={styles.imageBox}>
              <TouchableOpacity style={styles.imageDel} onPress={()=>{
                delImage(index)
              }}>
                <CloseIcon color="#333" size="2" />
              </TouchableOpacity>
              <Image style={[{ width:164},styles.image]} source={{uri:item.uri}} alt="123123" />
            </View>
          )
        })}
        {
          imgList && imgList.length < 6
          ?
          <View style={styles.addBtnBox}>
            <TouchableOpacity
              style={styles.addBtn}
              onPress={pickImage}
            >
              <View>
                <AddIcon size={7} color='#ccc'/>
              </View>
              
            </TouchableOpacity>
          </View>
          :
          ''
        }
      </View>


     
    </View>
  )
}

const PhoneInput = ({setData}:any)=>{
  const [ contact, setContact ] = useState('');
  const onChange = (text)=>{
    setContact(text)
    setData(text,4)
  }
  return (
    <View style={[styles.inputBox,styles.inputBoxPhone]}>
      <Text style={[styles.inpitTitle,{marginBottom:0}]}>联系方式</Text>
      <TextInput
        style={styles.input}
        keyboardType="phone-pad"
        placeholder='请输入'
        placeholderTextColor='#8E8E93'
        onChangeText={text => onChange(text)}
        value={contact}
      />
    </View>
  )
}

const SubBottn = ({navigation,data}:any) => {
  const toast = useToast();
  const subMit = ()=>{
    console.log(data)

    if(!data.content){
      // toast.show({
      //   description: "请输入反馈内容",
      //   placement: "top"
      // })
      showToast("", "", "请输入反馈内容");
      return
    }
    // const uploadImage = (image) => {
      const formData = new FormData();
      if(data.images && data.images.length){
        data.images.forEach((image:any)=>{
          formData.append('images', {
            uri: image.uri,
            type: image.type,
            name: image.fileName,
          });
        })
      }
      feedback(data,data.images&&data.images.length?formData:{}).then(res=>{
        console.log(res)
        if(res.code == 0){
          // toast.show({
          //   description: "提交成功",
          //   placement: "top"
          // })
          showToast("", "", "提交成功");
          setTimeout(() => {
            navigation.goBack()
          }, 1500);
        }
      })
  }


  


 


  return(
    <View>
      <TouchableOpacity
          style={styles.subBtn}
          onPress={
            ()=>{
              subMit()
            }
          }
        >
          <View>
            <Text style={styles.subBtnText}>提交反馈</Text>
          </View>
          
        </TouchableOpacity>
    </View>
  )
}

const FeedBack = ({navigation}:any) => {


  const { state, dispatch } = useGlobal();

  console.log(JSON.stringify(state))

  let data = {
    content:'',
    userId:state.userInfo.id,
    contact:'',
    type:'1',
    images:[]
  }

  console.log(data)

  const setData = (text:any,type:number)=>{
    if(type === 1){
      data.type = text
    }
    if(type === 2){
      data.content = text
    }
    if(type === 3){
      data.images = text
    }
    if(type == 4){
      data.contact = text
    }
  }

  return (
    <S.GrayContainer>
      <NativeBaseProvider >
        <View style={styles.container}>
          <Title navigation={navigation}/>
            <ScrollView style={{height:'100%'}} showsVerticalScrollIndicator={false} >
              <TypeList setData={setData} />
              <TextAreaBox setData={setData}/>
              <ImageUpload setData={setData}/>
              <PhoneInput setData={setData} />
              <SubBottn data={data} navigation={navigation}/>
            </ScrollView>
        </View>
      </NativeBaseProvider>
    </S.GrayContainer>
  );
};



export default FeedBack;

const styles = StyleSheet.create({
  container:{
    paddingHorizontal:18,
    flex:1
  },
  titleBox:{
    width:'100%',
    position:'relative',
    alignItems:'center',
    height:40,
    justifyContent:"center",
    marginBottom:16,
  },
  backBtn:{
    position:'absolute',
    left:0,
    backgroundColor:'#fff',
    width:40,
    height:40,
    display:'flex',
    alignItems:'center',
    justifyContent:'center',
    borderRadius:100,
    
    shadowColor: Platform.OS === 'android' ? '' : 'rgba(0, 0, 0, 0.08)', // 阴影颜色
    shadowOffset: { width: 0, height: 2 }, // 阴影偏移
    shadowOpacity: 1, // 阴影不透明度
    shadowRadius: 8, // 阴影半径
    elevation: 3, // 阴影深度
  },
  titlText:{
    fontSize:16,
    fontWeight:'600',
    color:'#000000'
  },



  levelOneTop: {
    backgroundColor: 'rgba(232, 232, 232, 1)',
    flexDirection: 'row',
    alignItems: 'center',
    borderRadius: 12,
    paddingHorizontal: 4,
    paddingVertical:4,
    justifyContent: 'space-between',
    
    
  },
  levelOneButton: {
    width: '30%',
    height: 32,
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: 10,
  },
  levelOneButtonActive:{
    elevation: 8, // 阴影深度
    shadowColor: 'rgba(0, 0, 0, 0.08)', // 阴影颜色
    shadowOffset: { width: 0, height: 2 }, // 阴影偏移
    shadowOpacity: 1, // 阴影不透明度
    shadowRadius: 8, // 阴影半径
    backgroundColor:'#fff',
  },
  buttonText:{
    fontSize:14,
    color:'#2C2C2E'
  },
  inputBox:{
    backgroundColor:'#fff',
    marginTop:16,
    padding:16,
    borderRadius:16,
  },
  inpitTitle:{
    fontSize:14,
    fontWeight:'700',
    color:'#2C2C2E',
    marginBottom:8,
  },
  iamgeContent:{
    width:'100%',
    flexDirection:'row',
    flexWrap:'wrap',
  },
  imageBox:{
    // flexDirection:'row',
    // flexWrap:'wrap',
    width: '25%',
    padding:5,
    position:'relative'
  },
  imageDel:{
    backgroundColor:'#eee',
    padding:4,
    borderRadius:100,
    position:'absolute',
    right:0,
    top:0,
    zIndex:1000,
  },
  image:{
    width: '100%',
    aspectRatio: 1, 
    borderRadius: 4
  },
  addBtnBox:{
    width: '25%',
    padding:5,
  },
  addBtn:{
    width: '100%',
    aspectRatio: 1, 
    borderRadius: 4,
    backgroundColor:'#F2F2F7',
    alignItems:'center',
    justifyContent:'center'
  },
  input:{
    fontSize:16,
    height:"100%",
    margin:0,
    padding:0,
    color:'#000'
  },
  inputBoxPhone:{
    flexDirection:'row',
    alignItems:'center',
    justifyContent:'space-between'
  },
  subBtn:{
    marginTop:50,
    width:'100%',
    backgroundColor:'#C6E0F7',
    borderRadius:16,
    height:50,
    alignItems:'center',
    justifyContent:'center'
  },
  subBtnText:{
    color:'#414F66',
    fontSize:14,
    fontWeight:'700'
  }

});